package com.hzsparrow.business.base.config;

import com.hzsparrow.business.base.contant.BaseBusinessCodeEnum;
import com.hzsparrow.business.base.contant.LoginUserEnum;
import com.hzsparrow.framework.model.result.ResultDTO;
import com.hzsparrow.framework.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Configuration
@ConditionalOnProperty(name = "hzsparrow.business.loginFilter.enable", havingValue = "true")
public class LoginFilterConfig {

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new Filter() {
            String[] notFilterUrl = {"/hzs/login", "/hzs/logout", "/hzs/getVerifyCode"};

            String[] staticView = {"/exview"};

            @Override
            public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
                String url = ((HttpServletRequest) servletRequest).getServletPath();
                boolean isFilter = true;
                for (String u : staticView) {
                    if (StringUtils.contains(url, u)) {
                        isFilter = false;
                        break;
                    }
                }
                for (String u : notFilterUrl) {
                    if (StringUtils.equals(u, url)) {
                        isFilter = false;
                        break;
                    }
                }
                if (isFilter) {
                    // 验证
                    Object user = ((HttpServletRequest) servletRequest).getSession().getAttribute(LoginUserEnum.SESSION_USER.getFlag());
                    if (user == null) {
                        ResultDTO<Object> result = ResultDTO.getDataFaild(BaseBusinessCodeEnum.NOT_LOGIN.getCode(), BaseBusinessCodeEnum.NOT_LOGIN.getMsg(), null);
                        servletResponse.setContentType("application/json;charset=utf-8");
                        servletResponse.getWriter().println(JsonUtils.serialize(result));
                        return;
                    }
                }
                filterChain.doFilter(servletRequest, servletResponse);
            }
        });
        bean.addUrlPatterns("/*");
        bean.setOrder(999);
        bean.setMatchAfter(true);
        return bean;
    }
}
